package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/*@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody*/
@Slf4j
@RestControllerAdvice(annotations ={RestController.class,Controller.class} )
//处理全局添加重复异常
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg=split[2]+"已经存在";
            return R.error(msg);
        }
        return R.error("未知错误!");
    }

    /**
     * 处理自定义异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustocmException.class)
    public R<String> exceptionHandler(CustocmException ex){
        return R.error(ex.getMessage());
    }

}
